<template>
  <!-- 中间表单内容 -->
  <el-row :gutter="formConf.gutter" class="form-row-container" :style="{ height: height }">
    <draggable
      :disabled="!isEdit"
      :class="flexClass"
      :list="drawingList"
      :animation="340"
      group="componentsGroup"
    >
      <el-col
        v-for="(item, index) in drawingList"
        :key="item.__config__.formId"
        :class="isEdit ? changClass(item, currentData, formConf) : ''"
        class="drawing-item"
        :span="item.__config__.span"
        @click.native.stop="activeFormItem(item, $event)"
      >
        <template v-if="isEdit">
          <!-- <div
            v-if="item.__config__.componentName"
            class="component-name"
          >{{ item.__config__.componentName }}</div>-->

          <span class="drawing-item-copy" title="复制" @click.stop="drawingItemCopy(item)">
            <i class="el-icon-copy-document" />
          </span>
          <span class="drawing-item-delete" title="删除" @click.stop="drawingItemDelete(item, index)">
            <i class="el-icon-delete" />
          </span>
        </template>
        <el-form-item
          :class="{
            'row-padding': item.__config__.tag === 'form-row-container',
            'mask-layer':
              (!enabled && item.__config__.tag !== 'form-row-container') ||
              item.readonly,
          }"
          :label="item.__config__.showLabel ? item.__config__.label : ''"
          :label-width="
            item.__config__.tag == 'form-row-container' ||
            !item.__config__.showLabel
              ? '0px'
              : item.__config__.labelWidth
              ? item.__config__.labelWidth + 'px'
              : ''
          "
          :required="
            item.__config__.required && !item.disabled && !item.readonly
          "
          :rules="formRules(item)"
          :prop="isEdit ? '' : item.__vModel__"
        >
          <!-- toCamelCase 需要将所有属性名更改为驼峰命名法，不然无法生效 -->
          <component
            v-model="item.__config__.defaultValue"
            :is="item.__config__.tag"
            v-bind="toCamelCase(deepClone(item))"
            :disabled="item.disabled || formConf.disabled"
            :formConf="formConf"
            :currentData.sync="activeData"
            :list.sync="item.__config__.children"
            :isEdit="isEdit"
            :enabled="enabled"
            @active="activeFormItem"
            @clone="handleClone"
          />
        </el-form-item>
      </el-col>
    </draggable>
  </el-row>
</template>

<script>
import draggable from "vuedraggable";
import { deepClone, toCamelCase } from "../../utils/index";
import {
  createFormItem,
  updateForm,
  changClass,
  formRules
} from "../../utils/index";

export default {
  name: "form-row-container",
  components: {
    draggable
  },
  props: {
    // 表单属性
    formConf: {
      type: Object,
      default: () => {}
    },
    // 当前选中表单
    currentData: {
      type: Object,
      default: () => {}
    },
    // 表单列表
    list: {
      type: Array,
      default: () => []
    },
    __config__: {
      type: Object,
      default: () => {}
    },
    // 是否为编辑模式
    isEdit: {
      type: Boolean,
      default: true
    },
    height: {
      type: String,
      default: ""
    },
    enabled: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      drawingList: [], // 初始化时默认选中表单组件
      activeData: {}, // 选中值
      formModel: {}
    };
  },

  computed: {
    flexClass() {
      let className = `el-row--flex is-align-${this.$attrs.align} is-justify-${this.$attrs.justify}`;
      return `${this.isEdit ? "drawing-board" : ""} ${
        this.$attrs.type == "flex" ? className : ""
      }`;
    }
  },

  watch: {
    // 当前选中的表单项数据
    currentData: {
      immediate: true,
      deep: true,
      handler(newValue) {
        if (newValue) {
          this.activeData = deepClone(newValue);
          updateForm(this.drawingList, newValue);
        }
      }
    },

    list: {
      immediate: true,
      deep: true,
      handler(newValue) {
        if (newValue) {
          this.drawingList = newValue;
          // this.drawingList = deepClone(newValue);
          // 当列表中的数据发生变化时，需要同步更改右侧属性
          const currentData = this.drawingList.find(
            item =>
              item.__config__.formId == this.activeData?.__config__?.formId
          );
          if (
            JSON.stringify(currentData) !== JSON.stringify(this.currentData)
          ) {
            this.activeFormItem(currentData);
          }
        }
      }
    },

    drawingList: {
      immediate: true,
      deep: true,
      handler(newValue) {
        if (JSON.stringify(newValue) !== JSON.stringify(this.list)) {
          // this.$emit("update:list", newValue);
          // this.$emit("change", newValue);
        }
      }
    }
  },

  methods: {
    toCamelCase,
    deepClone,
    changClass,
    formRules,

    // 选中某一表单项
    activeFormItem(currentItem, event) {
      event?.stopPropagation();
      // 需要将当前页所有数据渲染完了之后再更新当前选中
      this.$nextTick(() => {
        if (currentItem) {
          this.activeData = currentItem;
          this.$emit("update:currentData", this.activeData);
          this.$emit("active", currentItem, event);
        }
      });
    },
    // 复制表单项
    drawingItemCopy(item) {
      let clone = deepClone(item);
      clone = createFormItem(clone);
      this.handleClone(clone);
      // this.activeFormItem(clone);
    },
    handleClone(clone) {
      this.drawingList.push(clone);
    },
    // 删除表单项
    drawingItemDelete(item, index) {
      this.drawingList.splice(index, 1);
      const len = this.drawingList.length;
      if (len) {
        // this.activeFormItem(this.drawingList[len - 1]);
      }
    }
  }
};
</script>

<style lang="scss">
.form-row-container {
  min-height: 100px;
}
.row-padding {
  padding: 3px !important;
}
</style>
